package com.java.main.pdf;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.resolver.font.DefaultFontProvider;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.font.FontProvider;

import java.io.*;
import java.nio.charset.Charset;

public class Pdf2 {
    public static void main(String[] args) {
        String pdfFilePath = "D:\\Desktop\\托管3.0\\output.pdf";
        try(FileOutputStream pdfFileOutputStream = new FileOutputStream(pdfFilePath)) {

            File file = new File("D:\\Desktop\\托管3.0\\template.html"); // 替换成你的HTML文件路径
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), Charset.forName("GBK")));

            String line;
            StringBuilder htmlContent = new StringBuilder();
            while ((line = br.readLine()) != null) {
                htmlContent.append(line);
            }
            br.close();
            System.out.println(htmlContent.toString());

            PdfWriter pdfWriter = new PdfWriter(pdfFileOutputStream);

            // 创建PdfDocument对象
            PdfDocument pdfDocument = new PdfDocument(pdfWriter);
            pdfDocument.setDefaultPageSize(PageSize.A4);
            ConverterProperties pro = new ConverterProperties();
            FontProvider fontProvider = new DefaultFontProvider();
            fontProvider.addFont("simfang.ttf","UTF-8");
            pro.setFontProvider(fontProvider);
            // 使用HtmlConverter将HTML字符串转换为PDF
            HtmlConverter.convertToPdf(htmlContent.toString(), pdfDocument,pro);
            pdfWriter.close();
            pdfDocument.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
